<?php

namespace App\Http\Controllers\Util;

use App\Exceptions\ValidException;
use App\Notifications\RegisterNotify;
use App\User;
use Houdunwang\Aliyun\Aliyun;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CodeController extends Controller
{
    public $expire;
    public function __construct()
    {
        $this->expire=hd_config('bases.code_expire');
    }

    //手机发送验证码
    public function send(Request $request){
        //加载验证码，生成4位验证码
       $code=code_rand(4);
       $this->checkexpire();
       //判断发送来的是手机还是邮箱
//        filter_var($request->username)是邮箱返回true
        if(filter_var($request->username,FILTER_VALIDATE_EMAIL)){
            $type='email';
//            当是邮箱时给他发送邮件告知验证码
            $user=User::firstOrNew(['email'=>$request->username])?:new User();
            $user->notify(New RegisterNotify($code));
        }elseif ('/^\d{11}$/'){
        $type = 'mobile';
        $data = [
	//短信签名
	    'sign'     => '牧夢哟',
	    //短信模板
	    'template' => 'SMS_144145970',
	//前台提交来的手机号码
	    'mobile'   => $request->username,
	//模板变量
	    'vars'     => ["code" => $code],
    ];
        $res = Aliyun::instance('Sms')->send($data);
        }else{
            return ['code'=>$code,'message'=>'请输入正确的邮箱或者手机号码'];
        }
            $this->saveToSession($code,$type,$request);
            return ['code'=>1,'message'=>'验证码发送成功'];
    }
    //存储验证码
    public function saveToSession($code,$type,$request){
            session()->put('valid_code',[
               'code'=>$code,
                'type'=>$type,
                'username'=>$request->username,
                'expire'=>time()+$this->expire,//过期时间
            ]);
    }
    public function checkexpire(){
        $expire=session('valid_code.expire');
        if($expire&&$expire>time()){
            throw new ValidException('验证码发送过于频繁，请稍后再试');
        }
    }
}
